package com.example.demo_task_pool.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;

/**
 *
 */
@Configuration
public class TasKPoolConfig{

    @Bean("taskExecutor")
    public Executor TaskExecutor(){
        ThreadPoolTaskExecutor threadPoolTaskExecutor=new ThreadPoolTaskExecutor();
        //线程池创建时候初始化的线程数 核心线程数
        threadPoolTaskExecutor.setCorePoolSize(10);
        //线程池最大的线程数，只有缓冲队列满的时候才会申请超过核心线程数的线程
        threadPoolTaskExecutor.setMaxPoolSize(20);
        //用来执行缓冲任务的队列
        threadPoolTaskExecutor.setQueueCapacity(200);
        //允许线程空闲的时间 当超过了核心线程出之外的线程在空闲时间到达之后会被销毁
        threadPoolTaskExecutor.setKeepAliveSeconds(60);
        //线程池名的前缀
        threadPoolTaskExecutor.setThreadNamePrefix("taskExecutor-");
        //线程池对拒绝任务的处理策略
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        return threadPoolTaskExecutor;
    }
}
